#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

# Compile a given .sk file using the current compiler

import argparse
import common
import logging
import os
import subprocess
import sys
import common

logger = logging.getLogger(os.path.basename(__file__))

dir = os.path.abspath(os.path.dirname(__file__))
build_dir = common.build_dir
bin = os.path.join(build_dir, 'bin')

supported_backends = ['native']

def main():
    parser = argparse.ArgumentParser(
        description='Compile a Skip program',
        parents=[common.commonArguments(needsBackend=False, backend='native')])
    parser.add_argument('skip_program_unit', help='Skip program unit to compile')
    parser.add_argument('--output', '-o', required=False, help='Output executable name')
    args = common.parse_args(parser)

    backend = os.environ.get("BACKEND", 'native')
    via_backend = os.environ.get("VIA_BACKEND", bin)

    # keep until other backends are supported
    if backend not in supported_backends:
        sys.exit('Currently only supported backends are: ' + ' '.join(supported_backends))

    # build the appropriate backend
    cmd = ('ninja', '-C', build_dir) + {
        'native'    : ('skip_to_native', 'skip_to_llvm'),
        'js'        : ('skip_to_js',),
        'js_self'   : ('bin/skip_to_js.js',),
        'wasm'      : ('skip_to_native', 'skip_to_llvm', 'preamble32.tests.dep')
    }[backend]

    common.callHelper(cmd)

    compile_target = 'skip_' + backend + '_compile.py'

    print_skip_to_llvm = ('--print-skip-to-llvm',) if args.print_skip_to_llvm else ()

    cmd = (
        '/usr/bin/env',
        'python',
        os.path.join(dir, compile_target),
        '--output', os.path.abspath(args.output or args.skip_program_unit),
        '--via-backend', via_backend,
        os.path.basename(args.skip_program_unit)
        ) + print_skip_to_llvm

    common.callHelper(cmd, cwd=os.path.dirname(os.path.abspath(args.skip_program_unit)))


if __name__ == '__main__':
    main()
